﻿using System;
using ESRI.ArcGIS.ADF;
using ESRI.ArcGIS.Catalog;
using ESRI.ArcGIS.CatalogUI;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Geodatabase;

namespace BLLayer
{
    public class OpenGeodataSource
    {
        public IFeatureClass Open(string path, string name)
        {
            var workspace = GetWorkspace(path);
            var featureClass = workspace.OpenFeatureClass(name);
            ComReleaser.ReleaseCOMObject(workspace);
            return featureClass;
        }

        private IFeatureWorkspace GetWorkspace(string path)
        {
            IWorkspaceFactory2 factory;
            if (path.EndsWith(".mdb", StringComparison.OrdinalIgnoreCase))
                factory = new AccessWorkspaceFactoryClass();
            else if (path.EndsWith(".gdb", StringComparison.OrdinalIgnoreCase))
                factory = new FileGDBWorkspaceFactoryClass();
            else
                factory = new ShapefileWorkspaceFactoryClass();
            var lockControl = factory as IWorkspaceFactoryLockControl;
            if (lockControl.SchemaLockingEnabled)
                lockControl.DisableSchemaLocking();
            var workspace = factory.OpenFromFile(path, 0) as IFeatureWorkspace;
            ComReleaser.ReleaseCOMObject(factory);
            return workspace;
        }

        public IFeatureClass OpenShapeAndDataSets()
        {
            IGxObjectFilter shapefile = new GxFilterShapefilesClass();
            IGxObjectFilter datasets = new GxFilterDatasetsClass();
            IGxObjectFilterCollection filters = new GxDialogClass();
            filters.AddFilter(shapefile, false);
            filters.AddFilter(datasets, false);
            var dialog = (IGxDialog) filters;
            IEnumGxObject obj;
            if (!dialog.DoModalOpen(0, out obj)) return null;
            var path = dialog.FinalLocation.FullName;
            var name = obj.Next().Name;
            return Open(path, name);
        }
    }
}